﻿using System.Collections;
using System.Collections.Generic;
using System;

public abstract class NetSendEvent 
{
    public MessagePacket message;
    protected abstract ISerialize data { get; }

    public NetSendEvent()
    {
        message = new MessagePacket();
        message.seq = GetCurReqSeq();
        message.type = MessagePacketType.Event;
    }

    public void Write()
    {
        if (data != null)
        {
            byte[] messageData = data.Write();
            this.message.data = messageData;
        }
    }

    

    static int cur_seq = 0;
    public static int GetCurReqSeq()
    {
        return System.Threading.Interlocked.Increment(ref cur_seq);
    }

    protected virtual void OnSend(Remote  connect) { }

    public  void SendToRemote(Remote connect)
    {
        Write();

        OnSend(connect);

        connect.Send(message);
    }

    public void SendToRemotes(Remote[] connects)
    {
        Write();

        foreach (var connect in connects)
        {
            if (connect != null)
            {
                OnSend(connect);

                connect.Send(message);
            }
        }

    }


}


public abstract class NetSendToServer: NetSendEvent
{
    /// <summary>
    /// 发送时间，秒
    /// </summary>
    private double m_SendTime;
    public double sendTime => m_SendTime;

    public float timeOutSeconds = 3;

    public virtual bool needResponse => true;

    public abstract ResponseData NewResponseData();

    public Action<ResponseData> onResponse;
    public Action<NetSendToServer> onTimeOut;

    protected override void OnSend(Remote connect)
    {
        base.OnSend(connect);

       // GameDebug.Log(" connect.messageDispacher.AddRequest(this)");

        this.m_SendTime = CommonFunctions.GetTimeStampSeconds();

        if (needResponse)
        {
            //GameDebug.Log($"NetSendToServer AddRequest :{this.GetType().Name}  {this.GetHashCode()}   connect:{connect.clientId}");
            connect.messageDispacher.AddRequest(this);
        }
    }

    // public abstract NetMessageHandler GetResponseHandler();
    public override string ToString()
    {
        return $"key:{this.message?.key}  seq:{this.message?.seq}";
    }
}